<?php

class PictureController extends Controller
{
	
public function accessRules() {
		return array(
//			array('allow','actions'=>array('index'),'users'=>array('*')),
			array('deny','actions'=>array('upload','uploadForm'),'expression'=>'$user->isGuest'),
		
		
		);
	}
	
	public function actionUploadForm(){
		$this->layout='application.views.layouts.none';
		$this->render('/picture/uploadForm');
	}
	/**
	 * 
	 */
	public function actionUpload(){
		$this->layout='application.views.layouts.none';
		
		$model = new PictureUploadForm;
		
		$model->type =  isset($_REQUEST['type'])?$_REQUEST['type']:0;
		
		if(isset($_POST['PictureUploadForm'])){
			
			$model->attributes = $_POST['PictureUploadForm'];
			
			if($model->validate()){

				$result = array(); 
				$picture = new Picture;
				$picture->type = $model->type;
				$res = false; 
				 
				if( $file = CUploadedFile::getInstance($model,'file')) {

						$picture->filename = $file->tempName;
						$picture->metadata['ext']= $file->extensionName;
						$res = $picture->save(); 
				}
			 
				$result['result'] = $res;
				if($res){
					$result['id'] = $picture->_id .'';
				}else{
					$result['error'] = $picture->getErrors();
				}
		//		print_r($picture);
				echo function_exists('json_encode') ? json_encode($result) :CJSON::encode($result);
		//		$this->render('index',array('pid'=>123));
				
				Yii::app()->end();
			}
			
		}
		
		$this->render('/picture/upload',compact('model'));
	}
	/**
	 * original picture 
	 * @param unknown_type $pid
	 */
	public function actionUrl($pid){
	 	
	 	$img = Picture::model()->findByAttributes(array('_id'=>new MongoID($pid)));
		if($img){
			
			header('Content-Type: image/jpeg'); // JPG picture
			echo $img->getBytes();
		}
	}

	public function actionThumbnail($pid,$width=0,$height=0){
		 
		if($width == 0 || $height== 0 )
			$this->forward('url');
			
		
		$img = Picture::model()->findByAttributes(array('_id'=>new MongoID($pid)));
		if($img){
			$image = Yii::app()->image->getThumbFS($img ,$width,$height);
			$this->redirect(Yii::app()->request->baseUrl. $image);
		}

	}
	public function actionDefault($type = Picture::TYPE_AVATAR){
		
		
		echo Yii::app()->request->baseUrl. '/images/default/avatar.jpg';
		
	}
	public function actionList(){
		$imgs = Picture::model()->findAll();
		
		$this->render('list',array('imgs'=>$imgs));
	}
}